package com.hllxd.hism.star.basic.service.dao.http;

import com.alibaba.fastjson.JSON;
import com.hllxd.hism.star.basic.service.exception.BusinessException;
import com.github.pagehelper.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * Openai操作
 * @author lixiyong
 * @date 2019-01-02 10:11
 **/
@Slf4j
@Component("openaiApiMapper")
public class OpenaiApiMapperImpl implements OpenaiApiMapper {

//    private static String URL = "https://dohko-api.tiaofangzi.com";
//    private static String ACCESS_TOKEN = "p0r1o2d3u4c5t6O7u8t9Store0123456";

    @PostConstruct
    private void initialize() {
    }
    @Override public String handle(String text, String appid, String appUser) {
        if(StringUtil.isEmpty(text)) {
            log.warn("params is invalid.");
            throw new BusinessException("302","params is invalid.");
        }
        try {
            Param param = new Param();
            List<Message> messages = new ArrayList<>();
            messages.add(Message.build("system","请以markdown的形式返回答案"));
            messages.add(Message.build("user",text));
            param.messages = messages;
            String url = "https://api.aigcfun.com/api/v1/text?key=FCD3CPS08R2MJQBANM";
            String requestData = JSON.toJSONString(param);
            byte[] postData = requestData.getBytes(StandardCharsets.UTF_8);
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
                wr.write(postData);
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            AiResult obj2 = JSON.parseObject(response.toString(),AiResult.class);
//            System.out.println("choices: " + JSON.toJSONString(obj2.choices.get(0).text));
            return obj2.choices.get(0).text;
        }catch (Exception e) {
            log.warn("Exception: {}.",e.toString());
            return null;
        }
    }



    public static void main1(String[] args)  {
        OpenaiApiMapperImpl impl = new OpenaiApiMapperImpl();
        String result = impl.handle("中国运动员刘翔最近过的怎么？",null,null);
        log.info("{}",result);
    }

    public static void main2(String[] args) throws IOException {
        String apikey = "FCD3CPS08R2MJQBANM";
        String url = "https://api.aigcfun.com/translate?text=中国运动员刘翔最近过的怎么&target=zh&source=en&key=" + apikey;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            System.out.println("line: " + inputLine);
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
    }

    public static class Message {
        public String role;
        public String content;

        public static Message build(String role, String content) {
            Message thiz = new Message();
            thiz.role = role;
            thiz.content = content;
            return thiz;
        }
    }
    public static class Param{
        public List<Message> messages;
        public String model="gpt-3.5-turbo";
        public Long tokensLength;
    };

    public static class Choice {
        public Boolean block;
        public String finish_reason;
        public Integer index;
        public Message message;
        public String text;

    }
    public static class AiResult {
        public String id;
        public String object;
        public Integer errCode;
        public String error;
        public Integer created;
        public List<Choice> choices;
    }
    public static void main(String[] args) throws IOException {
        Param param = new Param();
        List<Message> messages = new ArrayList<>();
//        messages.add(Message.build("system","请以markdown的形式返回答案"));
        messages.add(Message.build("system","请以markdown的形式返回答案"));
        messages.add(Message.build("user","使用text2sql根据表和指标生成sql怎么实现"));
        param.messages = messages;

        String url = "https://api.aigcfun.com/api/v1/text?key=FCD3CPS08R2MJQBANM";
        String requestData = JSON.toJSONString(param);
        byte[] postData = requestData.getBytes(StandardCharsets.UTF_8);
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.write(postData);
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
        AiResult obj2 = JSON.parseObject(response.toString(),AiResult.class);
        System.out.println("choices: " + JSON.toJSONString(obj2.choices.get(0).text));
        
    }
}
